/*
 * Copyright 2010 Daniel Kurka
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package de.dhbw.vs.permachat.client.activities.chat;

import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceTokenizer;

import de.dhbw.vs.permachat.client.UserInformation;
import de.dhbw.vs.permachat.client.dto.ChatRoom;

/**
 * @author Daniel Kurka
 *
 */
public class ChatPlace extends Place {
	public static class ChatPlaceTokenizer implements PlaceTokenizer<ChatPlace> {
		private static final String SPLIT_CHAR = "&";

		@Override
		public ChatPlace getPlace(String token) {
			ChatRoom chatRoom = new ChatRoom();
			
			int splitCharIndex = token.indexOf(SPLIT_CHAR);
			if(splitCharIndex == -1){
				chatRoom.setName(token);
			} else{
				if(splitCharIndex == 0){
					//something went wrong, send user to login screen
					UserInformation.getUser().setName(null);
					throw new IllegalArgumentException("Parameter chat room must not be empty.");
				} else{
					chatRoom.setName(token.substring(0, splitCharIndex));
					if(token.length() > splitCharIndex + 1){
						UserInformation.getUser().setName(token.substring(splitCharIndex + 1));
					}
				}
			}
			
			
			return new ChatPlace(chatRoom);
		}

		@Override
		public String getToken(ChatPlace place) {
			String userName = UserInformation.getUser().getName();
			if(userName == null){
				return place.getChatRoom().getName();
			} else{
				return place.getChatRoom().getName() + SPLIT_CHAR + userName;
			}
		}

	}
	
	private ChatRoom chatRoom;
	
	public ChatPlace(ChatRoom chatRoom){
		this.chatRoom = chatRoom;
	}

	public ChatRoom getChatRoom() {
		return this.chatRoom;
	}
}
